package com.cjhhv.communal.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.cjhhv.base.model.ResponseDataModel;
import com.cjhhv.base.util.ResponseDataUtil;
import com.cjhhv.communal.model.FileDataModel;
import com.cjhhv.communal.service.FileDataService;
import com.cjhhv.communal.util.ReadFileUtil;
import com.cjhhv.communal.util.UploadImgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;


/**
 * 
 * <p>
 * Title: FileUploadAction.java
 * </p>
 * Description: 文件上传
 * <p>
 * Modify histoty:
 * 
 * @author cjh
 * @version 1.0
 */
@Controller
@RequestMapping("/fileUpload")
@Slf4j
public class FileUploadController {

    private FileDataService fileDataService;

    @Value("${file-upload.path}")
    private String resourcePath;

    @PostMapping("/uploadImg")
    @ResponseBody
    public ResponseDataModel uploadImg(HttpServletRequest request, HttpServletResponse response){
        File resourcePathFile = new File(resourcePath,"imgs");
        return this.upload(request,"imgUpload",resourcePathFile.getPath());
    }

    @GetMapping("/previewImg")
    public void previewImg(HttpServletRequest request, HttpServletResponse response) {
        this.fileRead(request, response, "图片");
    }


    private ResponseDataModel upload(HttpServletRequest request, String formFileName, String sourcePath){
        String businessMark = request.getParameter("businessMark");
        String businessId = request.getParameter("businessId");
        String createUser = request.getParameter("createUser");
        String createUserId = request.getParameter("createUserId");

        String dateDir = DateTimeFormatter.ofPattern("yyyy-MM-dd")
                .format(LocalDate.now());
        File sourcePathFile = new File(sourcePath,dateDir+"/"+businessMark);

        log.info("文件上传目录："+sourcePathFile.getPath());

        FileDataModel fileDataModel = UploadImgUtil.upload(request, formFileName, sourcePathFile.getPath(),true);
        fileDataModel.setFileId(UUID.randomUUID().toString());
        fileDataModel.setBusinessId(businessId);
        fileDataModel.setBusinessMark(businessMark);
        fileDataModel.setCreateUser(createUser);
        fileDataModel.setCreateUserId(createUserId);

        int result = this.fileDataService.saveFileData(fileDataModel);

        if(result>0){
            return ResponseDataUtil.createResponseData(true,"上传成功!",fileDataModel.getFileId());
        }

        return ResponseDataUtil.createResponseData(false,"上传失败!",null);
    }

    private void fileRead(HttpServletRequest request, HttpServletResponse response,String label) {
        try {
            String fileId = String.valueOf(request.getParameter("id"));
            if (StrUtil.isNotEmpty(fileId)) {
                FileDataModel fileData = this.fileDataService.queryFileDataById(fileId);
                if (!ObjectUtil.isEmpty(fileData)) {
                    ReadFileUtil.readFileToResponse(response, fileData.getFileUrl(), fileData.getFileName());
                }else{
                    log.error(label+"读取未成功");
                }

            }else{
                log.error(label+"读取未成功");
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error(label+"读取失败,错误——>" + e);
        }
    }




    public FileDataService getFileDataService() {
        return fileDataService;
    }

    @Autowired
    public void setFileDataService(FileDataService fileDataService) {
        this.fileDataService = fileDataService;
    }
}
